package com.cloudlegal.utils;

import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * 密码生成工具类
 * 用于生成BCrypt加密的密码字符串
 * 
 * @author CloudLegal Team
 * @since 2024-01-01
 */
@Component
public class PasswordGeneratorUtil {

    private final BCryptPasswordEncoder passwordEncoder;

    public PasswordGeneratorUtil() {
        this.passwordEncoder = new BCryptPasswordEncoder();
    }

    /**
     * 生成BCrypt加密密码
     * 
     * @param rawPassword 原始密码
     * @return 加密后的密码
     */
    public String encode(String rawPassword) {
        return passwordEncoder.encode(rawPassword);
    }

    /**
     * 验证密码
     * 
     * @param rawPassword 原始密码
     * @param encodedPassword 加密密码
     * @return 是否匹配
     */
    public boolean matches(String rawPassword, String encodedPassword) {
        return passwordEncoder.matches(rawPassword, encodedPassword);
    }

    /**
     * 生成常用密码的加密字符串
     * 
     * @return 密码映射表
     */
    public Map<String, String> generateCommonPasswords() {
        Map<String, String> passwords = new HashMap<>();
        
        String[] commonPasswords = {
            "123456", "admin", "password", "123456789", 
            "qwerty", "abc123", "111111", "123123",
            "admin123", "root", "user", "test"
        };
        
        for (String password : commonPasswords) {
            passwords.put(password, encode(password));
        }
        
        return passwords;
    }

    /**
     * 生成指定密码的多个不同加密结果
     * BCrypt每次生成的结果都不同，但都能验证成功
     * 
     * @param rawPassword 原始密码
     * @param count 生成数量
     * @return 加密结果列表
     */
    public Map<String, Object> generateMultipleHashes(String rawPassword, int count) {
        Map<String, Object> result = new HashMap<>();
        result.put("rawPassword", rawPassword);
        result.put("count", count);
        
        Map<String, String> hashes = new HashMap<>();
        for (int i = 1; i <= count; i++) {
            String hash = encode(rawPassword);
            hashes.put("hash" + i, hash);
            
            // 验证每个hash都能匹配原密码
            boolean matches = matches(rawPassword, hash);
            hashes.put("hash" + i + "_verified", String.valueOf(matches));
        }
        
        result.put("hashes", hashes);
        return result;
    }

    /**
     * 验证密码强度
     * 
     * @param password 密码
     * @return 强度信息
     */
    public Map<String, Object> checkPasswordStrength(String password) {
        Map<String, Object> strength = new HashMap<>();
        strength.put("password", password);
        strength.put("length", password.length());
        
        boolean hasLower = password.matches(".*[a-z].*");
        boolean hasUpper = password.matches(".*[A-Z].*");
        boolean hasDigit = password.matches(".*\\d.*");
        boolean hasSpecial = password.matches(".*[!@#$%^&*()_+\\-=\\[\\]{};':\"\\\\|,.<>\\/?].*");
        
        strength.put("hasLowercase", hasLower);
        strength.put("hasUppercase", hasUpper);
        strength.put("hasDigit", hasDigit);
        strength.put("hasSpecialChar", hasSpecial);
        
        int score = 0;
        if (password.length() >= 8) score++;
        if (password.length() >= 12) score++;
        if (hasLower) score++;
        if (hasUpper) score++;
        if (hasDigit) score++;
        if (hasSpecial) score++;
        
        String level;
        if (score >= 5) {
            level = "强";
        } else if (score >= 3) {
            level = "中";
        } else {
            level = "弱";
        }
        
        strength.put("score", score);
        strength.put("maxScore", 6);
        strength.put("level", level);
        strength.put("isStrong", score >= 5);
        
        return strength;
    }

    /**
     * 生成随机密码
     * 
     * @param length 密码长度
     * @param includeSpecialChars 是否包含特殊字符
     * @return 随机密码
     */
    public String generateRandomPassword(int length, boolean includeSpecialChars) {
        String lowercase = "abcdefghijklmnopqrstuvwxyz";
        String uppercase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        String digits = "0123456789";
        String special = "!@#$%^&*()_+-=[]{}|;:,.<>?";
        
        String chars = lowercase + uppercase + digits;
        if (includeSpecialChars) {
            chars += special;
        }
        
        StringBuilder password = new StringBuilder();
        for (int i = 0; i < length; i++) {
            int index = (int) (Math.random() * chars.length());
            password.append(chars.charAt(index));
        }
        
        return password.toString();
    }

    /**
     * 批量生成用户密码
     * 
     * @param usernames 用户名列表
     * @param defaultPassword 默认密码
     * @return 用户密码映射
     */
    public Map<String, String> generateUserPasswords(String[] usernames, String defaultPassword) {
        Map<String, String> userPasswords = new HashMap<>();
        
        for (String username : usernames) {
            String encodedPassword = encode(defaultPassword);
            userPasswords.put(username, encodedPassword);
        }
        
        return userPasswords;
    }

    /**
     * 生成SQL插入语句
     * 
     * @param userPasswords 用户密码映射
     * @param tableName 表名
     * @return SQL语句
     */
    public String generateInsertSQL(Map<String, String> userPasswords, String tableName) {
        StringBuilder sql = new StringBuilder();
        sql.append("-- 用户密码插入SQL\n");
        
        for (Map.Entry<String, String> entry : userPasswords.entrySet()) {
            sql.append("UPDATE ").append(tableName)
               .append(" SET password = '").append(entry.getValue())
               .append("' WHERE username = '").append(entry.getKey())
               .append("';\n");
        }
        
        return sql.toString();
    }
}
